// import axios from 'axios'
import Taro from '@tarojs/taro'

// 接口辅助方法, 返回 接口 操作 action
// _state 将会覆盖默认的 state
export default (apiConfig = {}) => {
  apiConfig = Object.assign(
    {
      method: 'POST',
      state: 'AJAX'
    },
    apiConfig
  )

  // 请求数据
  const request = params => {
    return {
      type: `REQUEST_${params._state || apiConfig.state}`,
      params
    }
  }

  // 收到数据
  const recieve = (params, data) => {
    return Object.assign(
      {},
      {
        params,
        type: `RECIEVE_${params._state || apiConfig.state}`,
        receivedAt: new Date()
      },
      data
    )
  }

  // 结果处理
  const handleResult = (dispatch, params, data) => {
    // 其他接口返回
    if (typeof data.ResponseData != 'undefined') {
      data.data = data.ResponseData
    }

    dispatch(
      recieve(params, {
        status: data.status,
        data: data.data,
        message: data.info
      })
    )

    return data
  }

  // restful api url处理
  const restfulApiHandle = (url, params) => {
    const keys = Object.keys(params)
    keys.map(key => {
      url = url.replace(`:${key}`, params[key])
    })
    return url
  }

  // 请求参数处理
  const searchParams = params => {
    const param = new URLSearchParams()
    const keys = Object.keys(params)
    keys.map(key => {
      if (typeof params[key] != 'undefined') param.set(key, params[key])
    })
    return param
  }
  //参数处理
  function getQueryString(params) {
    const esc = encodeURIComponent
    return Object.keys(params)
      .map(k => esc(k) + '=' + esc(params[k]))
      .join('&')
  }
  //fetch get和post 请求处理
  function soFetch(params) {
    const { method, headers, data } = params
    let qs = '',
      body
    ;['GET', 'DELETE'].indexOf(method) !== -1
      ? (qs = (params.url.indexOf('?') !== -1 ? '&' : '?') + getQueryString(data))
      : (body = searchParams(data)) // POST or PUT
    const url = params.url + qs
    return Taro.request(url, {
      method,
      headers,
      body
    })
  }

  return (params = {}, headers = {}, settings = {}) => {
    const url = restfulApiHandle(apiConfig.url, params)
    const commonParams = apiConfig.fullUrl
      ? {}
      : {
          // act,公共参数
        }
    params = Object.assign(commonParams, apiConfig.params, params)

    // 返回 promise
    return dispatch => {
      dispatch(request(params))
      const ajaxSettings = Object.assign(
        {
          url,
          method: apiConfig.method,
          data: params,
          headers: Object.assign(apiConfig.headers || {}, headers)
        },
        settings
      )
      return soFetch(ajaxSettings)
        .then(data => {
          // console.log(data, getState)
          data = handleResult(dispatch, params, data.data)
          return data
        })
        .catch(error => {
          // console.error(error)
          const data = handleResult(dispatch, params, error)
          return data
        })
    }
  }
}
